<template>
  <div>
    <!-- <button @click="clickCode">打开相机</button> -->
    <qrcode
      :qrcode="formData.qrcode"
      v-show="formData.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- <van-field right-icon="scan" /> -->
    <van-field
      v-show="!formData.qrcode"
      v-model="userIdText"
      @click="contactFn"
      :placeholder="placeholder"
      readonly
    >
      <template #button>
        <van-icon
          @click.stop="clickCode"
          size="30"
          color="#999"
          name="scan"
          style="margin-top: 2px"
        />
        <img
          v-if="EntityType == 'batchCode' && formData.key"
          src="~@/assets/img/filedClear.png"
          alt=""
          @click.stop="clickClose"
          class="filedClear"
          style="margin-top: -0.12rem"
        />
      </template>
    </van-field>
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
        value-key="key"
      />
    </van-popup>
  </div>
</template>

<script>
import * as dd from "dingtalk-jsapi";
// import VueCordova from 'vue-cordova'
// import Vue from 'vue'

export default {
  name: "Analysis",
  props: {
    columns: {
      type: Array,
      default: [],
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    EntityType: {
      type: String,
      default: "",
    },
    userIdText:{
      type: String,
      default: "",
    }
  },
  components: {
    qrcode: () => import("@/components/scanCode"),
  },
  data() {
    return {
      formData: {
        qrcode: false,
        code:{
          id:''
        }
      },
      torchActive: true,
      camera: "off",
      showPicker: false,
      value: "",
    };
  },
  mounted() {
    // Vue.use(VueCordova)
  },
  methods: {
    contactFn(){
      this.$emit('contactFn')
    },
    // getData() {
    //   getAction("/mess/messProductOrder/getOrderCodeDict", {
    //     status: "inProduction",
    //   }).then((res) => {
    //     console.log(res, "res");
    //     this.columns = res.result;
    //     this.showPicker = true;
    //   });
    // },
    propValue(value) {
      this.formData.value = value.id;
      this.formData.key = value.orderCode;
      this.$forceUpdate();
    },
    onConfirm(a, b) {
      console.log(a, b, "ab");
      if (typeof a == "undefined") {
        this.showPicker = false;
        return;
      }
      this.formData.value = a.value;
      this.formData.key = a.key;
      this.showPicker = false;
      this.$emit("changeScan", a, "select");
    },
    clickClose() {
      this.$emit("changeScan", false, "select");
    },
    // 打开相机
    clickCode() {
      let that = this;
      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          console.log("iwork扫码");
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          console.log("browser扫码");
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.formData.qrcode = true;
          that.camera = "rear";
          that.$emit("changeScan", that.formData);
          // Vue.cordova.on("deviceready", () => {
          //   const scanOption = {
          //     preferFrontCamera: false, // iOS and Android
          //     showFlipCameraButton: true, // iOS and Android
          //     showTorchButton: true, // iOS and Android
          //     torchOn: false, // Android, launch with the torch switched on (if available)
          //     saveHistory: false, // Android, save scan history (default false)
          //     prompt: "在扫描区域内放置条形码", // Android
          //     resultDisplayDuration: 0, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
          //     formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
          //     // orientation : "landscape", // Android only (portrait|landscape), default unset so it rotates with the device
          //     disableAnimations: true, // iOS
          //     disableSuccessBeep: false, // iOS and Android
          //   };
          //   //扫描二维码
          //   window.cordova.plugins.barcodeScanner.scan(
          //     (result) => {
          //       that.onDecode(result.text);
          //     },
          //     (error) => {
          //       console.err(error);
          //     },
          //     scanOption
          //   );
          // });
          break;
        case "dingding":
          console.log("dingding扫码");
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
              console.log(data);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
      // try {
      //   //入参
      //   var opt = {
      //     success: function (res) {
      //       console.log(JSON.stringify(res), "APP扫码数据");
      //       if (res.retCode == 0) {
      //         that.onDecode(res.retData);
      //       } else {
      //         that.$toast(res.retMsg);
      //       }
      //     },
      //     fail: function (err) {
      //       that.$toast("扫码失败！");
      //     },
      //   };
      //   //插件调用代码
      //   WorkHelper.scan(opt);
      // } catch (e) {
      //   // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
      //   that.formData.qrcode = true;
      //   that.camera = "rear";
      //   that.$emit("changeScan", that.formData);
      // }
    },
    // 扫码结果回调
    onDecode(result) {
      if(result){
        const str = result.replace(/'/g, '"') // 清理不可见字符
        this.formData.code = JSON.parse(str);
        this.$emit("changeScan", this.formData, "scan");
        this.turnCameraOff();
      }
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.formData.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },

    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped></style>
